<?php
/**
 * Created by PhpStorm.
 * User: My
 * Date: 2019/7/16
 * Time: 15:01
 */

namespace App\Http\Base;

use App\Http\Common\Helper\RedisHelper;
use Illuminate\Support\Facades\DB;

abstract class BaseRepository
{
    /**
     * 获取表名
     * @return mixed
     */
    protected abstract function getTableName();

    /**
     * 获取缓存key的前缀
     * @return mixed
     */
    protected abstract function getCachePrefix();

    /**
     * 子类实现保存方法
     * @param array $modelData
     * @return mixed
     */
    protected abstract function handleSave(array $modelData);

    /**
     * 子类实现保存方法
     * @param array $modelData
     * @return mixed
     */
    protected abstract function handleUpdate(array $modelData);

    /**
     * 子类实现删除方法
     * @param integer $id
     * @return mixed
     */
    protected abstract function handleDelete($id);

    public function save(array $modelData)
    {
        //清除当前类的缓存
        RedisHelper::deleteAll($this->getCachePrefix());
        return $this->handleSave($modelData);
    }

    public function update(array $modelData)
    {
        //清除当前类的缓存
        RedisHelper::deleteAll($this->getCachePrefix());
        return $this->handleUpdate($modelData);
    }

    public function deleted($id)
    {
        //清除当前类的缓存
        RedisHelper::deleteAll($this->getCachePrefix());
        return $this->handleDelete($id);
    }
    
    /**
     * 批量插入的方法
     * @param $dataArr
     * @return bool
     */
    public function batchInsertData(array $dataArr) {
        if (!$dataArr) {
            return false;
        }
        RedisHelper::deleteAll($this->getCachePrefix());
        return DB::table($this->getTableName())->insert($dataArr);
    }

    /**
     * 批量更新数据
     * @param array $multipleData
     * @return bool
     */
    public function batchUpdate(array $multipleData) {
        if (count($multipleData) > 0) {
            RedisHelper::deleteAll($this->getCachePrefix());
            // column or fields to update
            $updateColumn = array_keys($multipleData[0]);
            $referenceColumn = $updateColumn[0]; //e.g id
            unset($updateColumn[0]);
            $whereIn = "";
            $sql = "UPDATE " . $this->getTableName() . " SET ";
            foreach ($updateColumn as $uColumn) {
                $sql .= $uColumn . " = CASE ";

                foreach ($multipleData as $data) {
                    $sql .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
                }
                $sql .= "ELSE " . $uColumn . " END, ";
            }
            foreach ($multipleData as $data) {
                $whereIn .= "'" . $data[$referenceColumn] . "', ";
            }
            $sql = rtrim($sql, ", ") . " WHERE " . $referenceColumn . " IN (" . rtrim($whereIn, ', ') . ")";
            // Update
            return DB::update(DB::raw($sql));
        } else {
            return false;
        }
    }
}